# coding:utf-8

import requests


# 爬取python之禅
def craw():
    url = 'https://www.python.org/dev/peps/pep-0020/'
    res = requests.get(url)
    text = res.text
    print(text)
    with open('zen_of_python.txt', 'w') as f:
        # 官方
        f.write(text[text.find('<pre')+28:text.find('</pre>')-1])
        # 使用xpath或者re
        # path = '<pre class="literal-block">(.*?)</pre>'
        # f.write(re.compile(path).findall(text))
    print(text.find('<pre')+28, text.find('</pre>')-1)


# 翻译zen of python
def translate(word):
    url = 'http://fy.iciba.com/ajax.php?a=fy'
    data = {'f': 'auto', 't': 'auto', 'w': word}
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
    response = requests.post(url, data=data, headers=headers)
    return response.json()


# 获取翻译结果
def run(word):
    return translate(word)['content']['out']


def main():
    craw()
    with open('zen_of_python.txt', 'r') as f:
        result = [run(word) for word in f]
    with open('zen_of_python_zh_CN.txt', 'w') as f:
        for i in result:
            f.write(i + '\n')


if __name__ == '__main__':
    main()

